<?php
/**
 *
 * @Author nikm $
 *
 * @Date 2011-12-19 $
 */

if(!defined('FROM_INDEX')) exit('Invalid request');

function validate_request($request)
{
	include ROOT_PATH.'servlet/conf/auth.conf.php';

	$auth_key = isset($request['auth_key']) ? $request['auth_key'] : '';
	$auth_code = isset($request['auth_code']) ? $request['auth_code'] : '';
	
	if($auth_key && $auth_code && isset($auth[$auth_key]))
	{	
		$validate_code = get_auth_code($auth[$auth_key]['name'], $auth[$auth_key]['key']);

		if($auth_code == $validate_code)
		{
			return true;
		}
	}
	else
	{
		request_log($request, STATUS_E, LOG_LEVEL);
		return false;
	}
}

function get_auth_code($name, $key)
{
	$cache_key = md5("get_auth_code_$name"."_$key");
	
	$result = cache_get($key);
	if($result !== false)
	{
		return $result;
	}
	
	$group_key = 'n'.'i'.'k'.'m';
	$auth_key = md5(md5($name).'-'.md5($group_key).'-'.md5($key));
	$auth_key = substr($auth_key, 0, 3).substr($auth_key, 6, 3).substr($auth_key, 12, 3).substr($auth_key, 24, 3);
	
	cache_set($key, $auth_key, 3600*24*30); // one mounth
	
	return $auth_key;
}

/**
 *
 * Write request info into log file
 * @param array $request
 * @param string $status
 * @param int $log_level: 0 - no log, 1 - access log, 2 - request log
 */
function request_log($request, $status=STATUS_S, $log_level=1)
{
	if($log_level == 0)
	{
		return '';
	}

	$date = date('Y-m-d H:i:s');

	$path = ROOT_PATH.LOG_PATH.date('Y/m/d/');

	if(!file_exists($path))
	{
		mkdir($path, 0777, true);
	}
	
	include ROOT_PATH.'servlet/conf/auth.conf.php';
	$request_ip = get_client_ip();
	$auth_key = isset($request['auth_key']) ? $request['auth_key'] : '';
	$auth_name = isset($auth[$auth_key]) ? $auth[$auth_key]['name'] : 'null';
	
	$mod = isset($request['m']) ? $request['m'] : '';
	$act = isset($request['a']) ? $request['a'] : '';
	$func = $mod.'/'.$act;
	
	$end_time = microtime(true);
	$start_time = isset($request['start_time']) ? $request['start_time'] : $end_time;
	$time_use = round($end_time - $start_time, 2);
	
	$logInfo = '';
	if($log_level >= 1)
	{
		$logInfo = "Date Time: $date | IP: $request_ip | Auth: $auth_name | Time Use: $time_use | Call Function: $func";
		write_log($path.'access.log', $logInfo);
	}
	
	if($log_level >= 2)
	{		
		ob_start();
		$request = var_export($request, true);
		ob_clean();
		
		$logInfo = "Date Time: $date | Status: $status | IP: $request_ip | Auth: $auth_name | Time Use: $time_use | Call Function: $func | Request: $request \r\n";
		write_log($path.'request.log', $logInfo);
	}
}

function write_log($file, $msg)
{
	$handle = fopen($file, "a");
	$fileWrite = fwrite($handle, $msg."\n");
	fclose($handle);
}

/**
 * 
 * Show http response in json format
 * @param string $code: Message code
 * @param string $status: Response status
 */
function show_msg($request, $code, $status)
{	
	include_once ROOT_PATH .'servlet/conf/msg.conf.php';
	
	$result['version'] = API_VERSION;
	$result['status'] = $status;
	$result['message_code'] = (is_array($message) && isset($message[$code])) ? $code : '';

	$json = json_encode($result);
	
	request_log($_REQUEST, $status, LOG_LEVEL);
	
	echo $json;
	exit();
}

function show_response($requesr, $response)
{
	$json = '';
	if(is_array($response) && count($response) > 0)
	{
		$results = array_merge(array('version' => API_VERSION), $response);
		$json = @json_encode($results);
	}
	
	request_log($requesr, $response['status'], LOG_LEVEL);
	
	echo $json;
	exit();
}

/**
 * Parse request json string to array
 * @param string $json
 * @return array
 */
function parse_json($json)
{
	$result = false;

	if($json)
	{
		$json = str_replace('\n', '', $json);
		$json = stripslashes(trim($json));
		$result = @json_decode($json, true);
	}

	return $result;
}

function check_array($array)
{
	return (is_array($array) && count($array) > 0) ? true : false;
}

function get_client_ip()
{
	if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
		$ip = getenv("HTTP_CLIENT_IP");
	else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
		$ip = getenv("REMOTE_ADDR");
	else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
		$ip = $_SERVER['REMOTE_ADDR'];
	else
		$ip = '0.0.0.0';
	return preg_match('/^((25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)\.){3}(25[0-5]|2[0-4]\d|(1\d|[1-9])?\d)$/', $ip) ? $ip : '0.0.0.0';
}

function referer($default = '?')
{
	$DOMAIN = preg_replace("~^www\.~", '', strtolower(getenv('HTTP_HOST') ? getenv('HTTP_HOST') : $_SERVER['HTTP_HOST']));
	
	$referer = isset($_POST['referer']) ? $_POST['referer'] : (isset($_GET['referer']) ? $_GET['referer'] : '');
	
	if($referer == '')$referer = $_SERVER['HTTP_REFERER'];
	
	return $referer;
}

function random($length, $numeric = 0)
{
	mt_srand((double)microtime() * 1000000);
	if($numeric)
	{
		$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
	}
	else
	{
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen($chars) - 1;
		for($i = 0; $i < $length; $i++)
		{
			$hash .= $chars[mt_rand(0, $max)];
		}
	}
	return $hash;
}

function cut_string($str, $len)
{
	// 检查长度
	if (mb_strwidth($str, 'UTF-8')<=$len)
	{
		return $str;
	}

	
	// 截取
    $i 		= 0;   
    $tlen 	= 0;   
    $tstr 	= '';   
    
    while ($tlen < $len) 
    {   
        $chr 	= mb_substr($str, $i, 1, 'UTF-8');   
        $chrLen = ord($chr) > 127 ? 2 : 1;   
        
        if ($tlen + $chrLen > $len) break;   
        
        $tstr .= $chr;   
        $tlen += $chrLen;   
        $i ++;   
    }
    
    if ($tstr != $str) 
    {   
        $tstr .= '...';   
    }
    
    return $tstr; 
}

function read_dir($dir, $is_file=true)
{
	if(is_dir($dir) === false) return false;
	
	$dir = rtrim(str_replace("\\", "/", $dir), "/") ;
	$dirfp = @opendir($dir);
	if ($dirfp === false)
	{
		return false;
	}
	
	$abspath = '';
	$files = array();
	while(false !== ($file = @readdir($dirfp)))
	{
		if ($file != '.' and $file != '..')
		{
			$abspath = $dir . '/' . $file;

			if($is_file)
			{ // get all files
				if (is_file($abspath) !== false)
				{
					$files[] = $file ;
				}
				if(is_dir($abspath) !== false)
				{
					if ($children == '1')
					{
						$files = array_merge((array) $files, (array) read_dir($abspath, true));
					}
				}
			}
			else if(is_dir($abspath))
			{ //get sub folder list
				$files[] = $file ;
			}
		}
	}
	
	@closedir($dirfp);
	return $files;
}